package com.kaka.controller;

import com.kaka.bean.Result;
import com.kaka.bean.Student;
import com.kaka.bean.Teacher;
import com.kaka.util.MyJDBCUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;
import java.util.Random;

@WebServlet(name = "teacherController2", value = "/teacher2")
public class TeacherController2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        int tid = teacher.getTid();

        String sql = "select * from student where tid = ?";
        List<Student> students = MyJDBCUtil.dqlSQL(Student.class, sql, tid);
        Random random = new Random();
        int i = random.nextInt(students.size());
        Result.success(req, resp, students.get(i));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        int tid = teacher.getTid();

        String sql = "update teacher set password = ? where tid = ?";
        int i = MyJDBCUtil.dmlSQL(sql, password, tid);
        if (i == 1) {
            Result.success(req, resp, "修改成功");
        } else {
            Result.error(req, resp);
        }
    }
}
